﻿// Decompiled with JetBrains decompiler
// Type: TaleWorlds.CampaignSystem.Issues.LadysKnightOutIssueBehavior
// Assembly: TaleWorlds.CampaignSystem, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
// MVID: E85F8C15-4DF6-4E9C-A58A-29177E40D07A
// Assembly location: D:\steam\steamapps\common\Mount & Blade II Bannerlord\bin\Win64_Shipping_Client\TaleWorlds.CampaignSystem.dll

using Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using TaleWorlds.CampaignSystem.Actions;
using TaleWorlds.CampaignSystem.CharacterDevelopment;
using TaleWorlds.CampaignSystem.Conversation;
using TaleWorlds.CampaignSystem.Extensions;
using TaleWorlds.CampaignSystem.MapEvents;
using TaleWorlds.CampaignSystem.Party;
using TaleWorlds.CampaignSystem.Settlements;
using TaleWorlds.Core;
using TaleWorlds.Library;
using TaleWorlds.Localization;
using TaleWorlds.ObjectSystem;
using TaleWorlds.SaveSystem;

#nullable disable
namespace TaleWorlds.CampaignSystem.Issues
{
  public class LadysKnightOutIssueBehavior : CampaignBehaviorBase
  {
    private const IssueBase.IssueFrequency LadysKnightOutIssueFrequency = IssueBase.IssueFrequency.Common;

    public override void RegisterEvents()
    {
      CampaignEvents.OnCheckForIssueEvent.AddNonSerializedListener((object) this, new Action<Hero>(this.OnCheckForIssue));
    }

    public void OnCheckForIssue(Hero hero)
    {
      if (this.ConditionsHold(hero))
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(new PotentialIssueData.StartIssueDelegate(this.OnStartIssue), typeof (LadysKnightOutIssueBehavior.LadysKnightOutIssue), IssueBase.IssueFrequency.Common));
      else
        Campaign.Current.IssueManager.AddPotentialIssueData(hero, new PotentialIssueData(typeof (LadysKnightOutIssueBehavior.LadysKnightOutIssue), IssueBase.IssueFrequency.Common));
    }

    private bool ConditionsHold(Hero issueOwner)
    {
      return issueOwner.IsLord && issueOwner.IsFemale && issueOwner.GetTraitLevel(DefaultTraits.Mercy) < 0 && issueOwner.GetTraitLevel(DefaultTraits.PersonaSoftspoken) <= 0 && issueOwner.GetTraitLevel(DefaultTraits.PersonaCurt) <= 0 && issueOwner.Clan.Leader != issueOwner && issueOwner.Clan != Clan.PlayerClan && issueOwner.IsNoncombatant && issueOwner.CurrentSettlement != null && issueOwner.CurrentSettlement.IsTown && (double) issueOwner.CurrentSettlement.Town.Security <= 50.0;
    }

    private IssueBase OnStartIssue(in PotentialIssueData pid, Hero issueOwner)
    {
      return (IssueBase) new LadysKnightOutIssueBehavior.LadysKnightOutIssue(issueOwner);
    }

    public override void SyncData(IDataStore dataStore)
    {
    }

    public class LadysKnightOutIssue : IssueBase
    {
      private const int TakingQuestRelationLimit = -10;
      private const int QuestTimeLimit = 30;
      private const int IssueDuration = 30;
      private const int BaseRewardGold = 750;

      internal static void AutoGeneratedStaticCollectObjectsLadysKnightOutIssue(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      public override TextObject IssueBriefByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=M3af4N66}If you follow tournaments in this region, you'll know that I am a great devotee. I attend as many as I can - I love the spectacle, the tension... Despite this, I've never had a champion fight in my name, which is quite the fashion these days. Would you consider being my champion, {PLAYER.NAME}? I'm sure you could win glory for both of us.[if:convo_merry][ib:confident3]");
          StringHelpers.SetCharacterProperties("PLAYER", CharacterObject.PlayerCharacter, parent);
          return parent;
        }
      }

      public override TextObject IssueAcceptByPlayer
      {
        get => new TextObject("{=4nbnFMNZ}I can't promise to win, my lady.");
      }

      public override TextObject IssueLordSolutionExplanationByIssueGiver
      {
        get
        {
          return new TextObject("{=SzIPvqLk}Of course not. If you don't wish to fight yourself - and I understand you might be quite busy - you could use your influence to convince one of the nobles of this realm to hold their next tournament in my honor.[ib:demure2][if:convo_merry]");
        }
      }

      public override TextObject IssuePlayerResponseAfterLordExplanation
      {
        get
        {
          return new TextObject("{=MuwmsOSn}I will consider this. What does it mean to be your champion?");
        }
      }

      public override TextObject IssueQuestSolutionExplanationByIssueGiver
      {
        get
        {
          TextObject explanationByIssueGiver = new TextObject("{=Pnc8ToV1}Just participate in a future tournament in this realm, and say you dedicate your victories to me. {TOURNAMENT_ROUND_GOAL}[ib:hip]");
          if (this.TournamentRoundGoal == 5)
          {
            explanationByIssueGiver.SetTextVariable("TOURNAMENT_ROUND_GOAL", new TextObject("{=2Rzw16OX}If you can advance to win the tournament, I'm sure that will do us both honor.[ib:hip2][if:convo_relaxed_happy]"));
          }
          else
          {
            TextObject variable = new TextObject("{=al27CmYV}If you can advance to reach round {ROUND_COUNT}, I'm sure that will do us both honor.[if:convo_calm_friendly][ib:demure]");
            variable.SetTextVariable("ROUND_COUNT", this.TournamentRoundGoal);
            explanationByIssueGiver.SetTextVariable("TOURNAMENT_ROUND_GOAL", variable);
          }
          return explanationByIssueGiver;
        }
      }

      public override TextObject IssueQuestSolutionAcceptByPlayer
      {
        get
        {
          if (this.TournamentRoundGoal == 5)
            return new TextObject("{=YArbm6TV}Then I will enter the tournament and win it, my lady.");
          TextObject solutionAcceptByPlayer = new TextObject("{=w3rcCibp}Then I will enter the tournament and reach round {ROUND_COUNT} my lady.");
          solutionAcceptByPlayer.SetTextVariable("ROUND_COUNT", this.TournamentRoundGoal);
          return solutionAcceptByPlayer;
        }
      }

      public override TextObject IssueLordSolutionAcceptByPlayer
      {
        get
        {
          return new TextObject("{=0WOPfOIH}I'm afraid I don't have time to fight but I can use my influence.");
        }
      }

      public override TextObject IssueLordSolutionResponseByIssueGiver
      {
        get
        {
          TextObject parent = new TextObject("{=ZZ7Q3VOG}Thank you my {?PLAYER.GENDER}lady{?}lord{\\?}. I am indeed honored.");
          StringHelpers.SetCharacterProperties("PLAYER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      protected override TextObject LordSolutionStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=EnhdXpQf}{ISSUE_OWNER.LINK} from {ISSUE_OWNER.FACTION}, has told you about of the tournament at the {ISSUE_OWNER_SETTLEMENT}. She wants you to be her champion. {TOURNAMENT_ROUND_GOAL}");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent, true);
          parent.SetTextVariable("ISSUE_OWNER_SETTLEMENT", this.IssueOwner.CurrentSettlement.EncyclopediaLinkWithName);
          if (this.TournamentRoundGoal == 5)
          {
            parent.SetTextVariable("TOURNAMENT_ROUND_GOAL", new TextObject("{=YbzHpFiu}She expects you to win the tournament."));
          }
          else
          {
            TextObject variable = new TextObject("{=5qkTxOJ5}She expects you to reach round {ROUND_COUNT}.");
            variable.SetTextVariable("ROUND_COUNT", this.TournamentRoundGoal);
            parent.SetTextVariable("TOURNAMENT_ROUND_GOAL", variable);
          }
          return parent;
        }
      }

      protected override TextObject LordSolutionCounterOfferRefuseLog
      {
        get
        {
          TextObject parent = new TextObject("{=IPg30HIs}You told {ISSUE_OWNER.LINK} that instead of her request, the next tournament held will be held in her honor.");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      public override bool IsThereAlternativeSolution => false;

      public override bool IsThereLordSolution => true;

      public override TextObject Title => new TextObject("{=a4XGmdd9}Lady's Knight Out");

      public override TextObject Description
      {
        get
        {
          TextObject parent = new TextObject("{=oBl6SxeJ}{ISSUE_OWNER.LINK} wants you to participate in a tournament in her name.");
          StringHelpers.SetCharacterProperties("ISSUE_OWNER", this.IssueOwner.CharacterObject, parent);
          return parent;
        }
      }

      private int TournamentRoundGoal
      {
        get
        {
          if ((double) this.IssueDifficultyMultiplier > 0.699999988079071)
            return 5;
          if (0.699999988079071 >= (double) this.IssueDifficultyMultiplier && (double) this.IssueDifficultyMultiplier > 0.5)
            return 4;
          return 0.5 >= (double) this.IssueDifficultyMultiplier && (double) this.IssueDifficultyMultiplier > 0.20000000298023224 ? 3 : 2;
        }
      }

      public override int NeededInfluenceForLordSolution
      {
        get => 15 + MathF.Ceiling(30f * this.IssueDifficultyMultiplier);
      }

      public LadysKnightOutIssue(Hero issueOwner)
        : base(issueOwner, CampaignTime.DaysFromNow(30f))
      {
      }

      protected override float GetIssueEffectAmountInternal(IssueEffect issueEffect)
      {
        if (issueEffect == DefaultIssueEffects.SettlementLoyalty)
          return -0.2f;
        return issueEffect == DefaultIssueEffects.ClanInfluence ? -0.1f : 0.0f;
      }

      protected override void OnGameLoad()
      {
      }

      protected override void HourlyTick()
      {
      }

      protected override QuestBase GenerateIssueQuest(string questId)
      {
        return (QuestBase) new LadysKnightOutIssueBehavior.LadysKnightOutIssueQuest(questId, this.IssueOwner, CampaignTime.DaysFromNow(30f), this.IssueDifficultyMultiplier, 750);
      }

      public override IssueBase.IssueFrequency GetFrequency() => IssueBase.IssueFrequency.Common;

      protected override bool CanPlayerTakeQuestConditions(
        Hero issueGiver,
        out IssueBase.PreconditionFlags flag,
        out Hero relationHero,
        out SkillObject skill)
      {
        skill = (SkillObject) null;
        relationHero = (Hero) null;
        flag = IssueBase.PreconditionFlags.None;
        if ((double) issueGiver.GetRelationWithPlayer() < -10.0)
        {
          flag |= IssueBase.PreconditionFlags.Relation;
          relationHero = issueGiver;
        }
        if (FactionManager.IsAtWarAgainstFaction(issueGiver.CurrentSettlement.MapFaction, Hero.MainHero.MapFaction))
          flag |= IssueBase.PreconditionFlags.AtWar;
        return flag == IssueBase.PreconditionFlags.None;
      }

      public override bool IssueStayAliveConditions()
      {
        return this.IssueOwner.IsNoncombatant && this.IssueOwner.CurrentSettlement != null && this.IssueOwner.CurrentSettlement.IsTown && (double) this.IssueOwner.CurrentSettlement.Town.Security <= 80.0;
      }

      protected override void CompleteIssueWithTimedOutConsequences()
      {
      }

      protected override void LordSolutionConsequenceWithRefuseCounterOffer()
      {
        Clan.PlayerClan.AddRenown(7f);
        ChangeRelationAction.ApplyPlayerRelation(this.IssueOwner, 5);
      }
    }

    public class LadysKnightOutIssueQuest : QuestBase
    {
      [SaveableField(1)]
      private readonly float _difficultyMultiplier;
      [SaveableField(2)]
      private Town _tournamentTown;

      internal static void AutoGeneratedStaticCollectObjectsLadysKnightOutIssueQuest(
        object o,
        List<object> collectedObjects)
      {
        ((MBObjectBase) o).AutoGeneratedInstanceCollectObjects(collectedObjects);
      }

      protected override void AutoGeneratedInstanceCollectObjects(List<object> collectedObjects)
      {
        base.AutoGeneratedInstanceCollectObjects(collectedObjects);
        collectedObjects.Add((object) this._tournamentTown);
      }

      internal static object AutoGeneratedGetMemberValue_difficultyMultiplier(object o)
      {
        return (object) ((LadysKnightOutIssueBehavior.LadysKnightOutIssueQuest) o)._difficultyMultiplier;
      }

      internal static object AutoGeneratedGetMemberValue_tournamentTown(object o)
      {
        return (object) ((LadysKnightOutIssueBehavior.LadysKnightOutIssueQuest) o)._tournamentTown;
      }

      private int TournamentRoundGoal
      {
        get
        {
          if ((double) this._difficultyMultiplier > 0.699999988079071)
            return 5;
          if (0.699999988079071 >= (double) this._difficultyMultiplier && (double) this._difficultyMultiplier > 0.5)
            return 4;
          return 0.5 >= (double) this._difficultyMultiplier && (double) this._difficultyMultiplier > 0.20000000298023224 ? 3 : 2;
        }
      }

      private TextObject QuestStartLog
      {
        get
        {
          TextObject parent = new TextObject("{=kqgadhCF}{QUEST_GIVER.LINK} from {QUEST_GIVER.FACTION}, has asked you to be her champion in an upcoming tournament. {TOURNAMENT_ROUND_GOAL} \nYou told her that you will honor her name in a tournament.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent, true);
          parent.SetTextVariable("QUEST_GIVER_TOWN", this.QuestGiver.CurrentSettlement.EncyclopediaLinkWithName);
          if (this.TournamentRoundGoal == 5)
          {
            parent.SetTextVariable("TOURNAMENT_ROUND_GOAL", new TextObject("{=r8VcYkUf}She expects you to fight in her name and win the tournament."));
          }
          else
          {
            TextObject variable = new TextObject("{=edJtO2ua}She expects you to fight in her name and reach at least {ROUND_COUNT}.");
            variable.SetTextVariable("ROUND_COUNT", this.TournamentRoundGoal);
            parent.SetTextVariable("TOURNAMENT_ROUND_GOAL", variable);
          }
          return parent;
        }
      }

      private TextObject PlayerWinsTournamentSuccessLog
      {
        get
        {
          TextObject parent = new TextObject("{=QAg8DQy6}You received a message from {QUEST_GIVER.LINK}.\n \"Thank you for fighting so valiantly in my name. Please take these {REWARD} denars with our gratitude.\"");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          parent.SetTextVariable("REWARD", this.RewardGold);
          return parent;
        }
      }

      private TextObject PlayerFailedToReachTournamentLevelLog
      {
        get
        {
          TextObject parent = new TextObject("{=04ti5hcX}{TOURNAMENT_ROUND_GOAL}{QUEST_GIVER.LINK} will certainly be disappointed.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          if (this.TournamentRoundGoal == 5)
          {
            parent.SetTextVariable("TOURNAMENT_ROUND_GOAL", new TextObject("{=tDNiLiRM}You have failed to win the tournament. "));
          }
          else
          {
            TextObject variable = new TextObject("{=CxKC5gqq}You have failed to reach round {ROUND_COUNT} in the tournament. ");
            variable.SetTextVariable("ROUND_COUNT", this.TournamentRoundGoal);
            parent.SetTextVariable("TOURNAMENT_ROUND_GOAL", variable);
          }
          return parent;
        }
      }

      private TextObject PlayerFailedToJoinTournamentLog
      {
        get
        {
          TextObject parent = new TextObject("{=D40RPEbz}You have failed to enter a tournament in time. {QUEST_GIVER.LINK} will certainly be disappointed.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject WarDeclaredOnQuestGiversFactionCancelLog
      {
        get
        {
          TextObject parent = new TextObject("{=zh3Wf6bu}You are now at war with {QUEST_GIVER.LINK}'s faction. Quest is canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject PlayerDeclaredWarQuestLogText
      {
        get
        {
          TextObject parent = new TextObject("{=bqeWVVEE}Your actions have started a war with {QUEST_GIVER.LINK}'s faction. {?QUEST_GIVER.GENDER}She{?}He{\\?} cancels your agreement and the quest is a failure.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestGiverIsDeadCancelLog
      {
        get
        {
          TextObject parent = new TextObject("{=2Ju7Eduu}{QUEST_GIVER.LINK} has died. Your quest is canceled.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject QuestGiverLeftSettlementCancelLog
      {
        get
        {
          TextObject parent = new TextObject("{=1RBxhh4W}{QUEST_GIVER.LINK} is not avaliable for this quest anymore.");
          StringHelpers.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject, parent);
          return parent;
        }
      }

      private TextObject MainHeroAttackedLadysClansVillageLog
      {
        get
        {
          TextObject to = new TextObject("{=Qft5pfYr}You have been accused of a crime, and {QUEST_GIVER.LINK} has declared that you are no longer her champion.");
          to.SetCharacterProperties("QUEST_GIVER", this.QuestGiver.CharacterObject);
          return to;
        }
      }

      public override TextObject Title => new TextObject("{=a4XGmdd9}Lady's Knight Out");

      public override bool IsRemainingTimeHidden => false;

      public LadysKnightOutIssueQuest(
        string questId,
        Hero questGiver,
        CampaignTime duration,
        float issueDifficultyMultiplier,
        int rewardGold)
        : base(questId, questGiver, duration, rewardGold)
      {
        this._difficultyMultiplier = issueDifficultyMultiplier;
        this._tournamentTown = (Town) null;
        this.SetDialogs();
        this.InitializeQuestOnCreation();
      }

      protected override void InitializeQuestOnGameLoad() => this.SetDialogs();

      protected override void HourlyTick()
      {
      }

      protected override void RegisterEvents()
      {
        CampaignEvents.PlayerStartedTournamentMatch.AddNonSerializedListener((object) this, new Action<Town>(this.OnPlayerStartedTournamentMatch));
        CampaignEvents.PlayerEliminatedFromTournament.AddNonSerializedListener((object) this, new Action<int, Town>(this.OnPlayerEliminatedFromTournament));
        CampaignEvents.TournamentFinished.AddNonSerializedListener((object) this, new Action<CharacterObject, MBReadOnlyList<CharacterObject>, Town, ItemObject>(this.OnTournamentFinished));
        CampaignEvents.WarDeclared.AddNonSerializedListener((object) this, new Action<IFaction, IFaction, DeclareWarAction.DeclareWarDetail>(this.OnWarDeclared));
        CampaignEvents.OnClanChangedKingdomEvent.AddNonSerializedListener((object) this, new Action<Clan, Kingdom, Kingdom, ChangeKingdomAction.ChangeKingdomActionDetail, bool>(this.OnClanChangedKingdom));
        CampaignEvents.HeroKilledEvent.AddNonSerializedListener((object) this, new Action<Hero, Hero, KillCharacterAction.KillCharacterActionDetail, bool>(this.OnHeroKilled));
        CampaignEvents.OnSettlementLeftEvent.AddNonSerializedListener((object) this, new Action<MobileParty, Settlement>(this.OnSettlementLeft));
        CampaignEvents.MapEventStarted.AddNonSerializedListener((object) this, new Action<MapEvent, PartyBase, PartyBase>(this.OnMapEventStarted));
      }

      private void OnMapEventStarted(
        MapEvent mapEvent,
        PartyBase attackerParty,
        PartyBase defenderParty)
      {
        if ((mapEvent.IsForcingSupplies || mapEvent.IsForcingVolunteers || mapEvent.IsRaid) && attackerParty == PartyBase.MainParty && mapEvent.MapEventSettlement.IsVillage && mapEvent.MapEventSettlement.OwnerClan == this.QuestGiver.Clan)
        {
          this.CriminalActionPerformedTowardsSettlement();
        }
        else
        {
          if (!QuestHelper.CheckMinorMajorCoercion((QuestBase) this, mapEvent, attackerParty))
            return;
          QuestHelper.ApplyGenericMinorMajorCoercionConsequences((QuestBase) this, mapEvent);
        }
      }

      protected override void OnTimedOut()
      {
        base.OnTimedOut();
        this.PlayerFailedToJoinTournamentInTime();
      }

      protected override void SetDialogs()
      {
        this.OfferDialogFlow = DialogFlow.CreateDialogFlow("issue_classic_quest_start").NpcLine(new TextObject("{=at0iWxo1}It is exciting to think a warrior of your caliber will be my champion. {TOURNAMENT_ROUND_GOAL}")).Condition(new ConversationSentence.OnConditionDelegate(this.QuestAcceptedCondition)).Consequence(new ConversationSentence.OnConsequenceDelegate(this.QuestAcceptedConsequences)).CloseDialog();
        this.DiscussDialogFlow = DialogFlow.CreateDialogFlow("quest_discuss").NpcLine(new TextObject("{=iPcbFoDx}Are you prepared for the tournament? Eating well? Staying healthy?")).Condition((ConversationSentence.OnConditionDelegate) (() => CharacterObject.OneToOneConversationCharacter == this.QuestGiver.CharacterObject)).PlayerLine(new TextObject("{=YOmuyrIt}Do you know if there is a tournament starting soon?")).BeginNpcOptions().NpcOption(new TextObject("{=CeYwClaG}Yes, there is one starting at {NEARBY_TOURNAMENTS_LIST}. I am sure the arena master can explain the rules, if you need to know them."), new ConversationSentence.OnConditionDelegate(this.NpcTournamentLocationCondition)).CloseDialog().NpcDefaultOption("{=sUfSCLQx}Sadly, I've heard no news of an upcoming tournament. I am sure one will be held before too long.").CloseDialog().EndNpcOptions().CloseDialog();
      }

      private bool QuestAcceptedCondition()
      {
        if (this.TournamentRoundGoal == 5)
        {
          MBTextManager.SetTextVariable("TOURNAMENT_ROUND_GOAL", new TextObject("{=nctTI5mv}I have every reason to believe you'll win the tournament."), false);
        }
        else
        {
          TextObject text = new TextObject("{=3FMvLhWV}I have every reason to believe you'll reach round {ROUND_COUNT}.");
          text.SetTextVariable("ROUND_COUNT", this.TournamentRoundGoal);
          MBTextManager.SetTextVariable("TOURNAMENT_ROUND_GOAL", text, false);
        }
        return CharacterObject.OneToOneConversationCharacter == this.QuestGiver.CharacterObject;
      }

      private void QuestAcceptedConsequences()
      {
        this.StartQuest();
        this.AddLog(this.QuestStartLog);
      }

      private bool NpcTournamentLocationCondition()
      {
        List<Town> list = Town.AllTowns.Where<Town>((Func<Town, bool>) (x => Campaign.Current.TournamentManager.GetTournamentGame(x) != null && x != Settlement.CurrentSettlement.Town)).ToList<Town>().OrderBy<Town, float>((Func<Town, float>) (x => x.Settlement.Position2D.DistanceSquared(Settlement.CurrentSettlement.Position2D))).ToList<Town>();
        if (list.Count <= 0)
          return false;
        MBTextManager.SetTextVariable("NEARBY_TOURNAMENTS_LIST", list[0].Name, false);
        return true;
      }

      private void OnPlayerStartedTournamentMatch(Town town) => this._tournamentTown = town;

      private void OnPlayerEliminatedFromTournament(int round, Town settlement)
      {
        if (this.TournamentRoundGoal > round + 1)
          this.PlayerCouldntReachedTournamentRoundGoal();
        else
          this.PlayerReachedTournamentRoundGoal();
      }

      private void OnTournamentFinished(
        CharacterObject winner,
        MBReadOnlyList<CharacterObject> participants,
        Town town,
        ItemObject prize)
      {
        if (town != this._tournamentTown || winner != CharacterObject.PlayerCharacter)
          return;
        this.PlayerReachedTournamentRoundGoal();
      }

      private void OnClanChangedKingdom(
        Clan clan,
        Kingdom oldKingdom,
        Kingdom newKingdom,
        ChangeKingdomAction.ChangeKingdomActionDetail detail,
        bool showNotification = true)
      {
        if (!this.QuestGiver.MapFaction.IsAtWarWith(Hero.MainHero.MapFaction))
          return;
        this.CompleteQuestWithCancel(this.WarDeclaredOnQuestGiversFactionCancelLog);
      }

      private void OnWarDeclared(
        IFaction faction1,
        IFaction faction2,
        DeclareWarAction.DeclareWarDetail detail)
      {
        QuestHelper.CheckWarDeclarationAndFailOrCancelTheQuest((QuestBase) this, faction1, faction2, detail, this.PlayerDeclaredWarQuestLogText, this.WarDeclaredOnQuestGiversFactionCancelLog);
      }

      private void OnHeroKilled(
        Hero victim,
        Hero killer,
        KillCharacterAction.KillCharacterActionDetail detail,
        bool showNotification)
      {
        if (victim != this.QuestGiver)
          return;
        this.QuestGiverIsDead();
      }

      private void OnSettlementLeft(MobileParty party, Settlement settlement)
      {
        if (this.QuestGiver.CurrentSettlement != null)
          return;
        this.QuestGiverLeftSettlement();
      }

      private void PlayerReachedTournamentRoundGoal()
      {
        this.AddLog(this.PlayerWinsTournamentSuccessLog);
        Clan.PlayerClan.AddRenown(1f);
        GiveGoldAction.ApplyBetweenCharacters((Hero) null, Hero.MainHero, this.RewardGold);
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, 5);
        this.CompleteQuestWithSuccess();
      }

      private void PlayerCouldntReachedTournamentRoundGoal()
      {
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, -5);
        this.CompleteQuestWithFail(this.PlayerFailedToReachTournamentLevelLog);
      }

      private void PlayerFailedToJoinTournamentInTime()
      {
        this.AddLog(this.PlayerFailedToJoinTournamentLog);
        ChangeRelationAction.ApplyPlayerRelation(this.QuestGiver, -5);
      }

      private void QuestGiverIsDead()
      {
        this.CompleteQuestWithCancel(this.QuestGiverIsDeadCancelLog);
      }

      private void QuestGiverLeftSettlement()
      {
        this.CompleteQuestWithCancel(this.QuestGiverLeftSettlementCancelLog);
      }

      private void CriminalActionPerformedTowardsSettlement()
      {
        this.RelationshipChangeWithQuestGiver = -5;
        TraitLevelingHelper.OnIssueSolvedThroughQuest(Hero.MainHero, new Tuple<TraitObject, int>[1]
        {
          new Tuple<TraitObject, int>(DefaultTraits.Honor, -50)
        });
        this.CompleteQuestWithFail(this.MainHeroAttackedLadysClansVillageLog);
      }
    }

    public class LadysKnightOutIssueTypeDefiner : SaveableTypeDefiner
    {
      public LadysKnightOutIssueTypeDefiner()
        : base(585700)
      {
      }

      protected override void DefineClassTypes()
      {
        this.AddClassDefinition(typeof (LadysKnightOutIssueBehavior.LadysKnightOutIssue), 1);
        this.AddClassDefinition(typeof (LadysKnightOutIssueBehavior.LadysKnightOutIssueQuest), 2);
      }
    }
  }
}
